/*
$(document).ready(function () {
	$(window).bind('orientationchange', function() {
		if (window.orientation % 180 == 0) {
			$(document.body).css("-webkit-transform-origin", "").css("-webkit-transform", "");
		} else {
			if (window.orientation > 0) { //clockwise
				$(document.body).css("-webkit-transform-origin", "200px 190px").css("-webkit-transform",  "rotate(-90deg)");
			} else {
				$(document.body).css("-webkit-transform-origin", "280px 190px").css("-webkit-transform",  "rotate(90deg)");
			}
		}
	}).trigger('orientationchange');
});
*/
/*
$(document).bind("orientationchange", function(event) {
	console.log("orientationchange");
	if (event.orientation == "portrait") {
		getViewport().setWH(320, 460);
	}
	if (event.orientation == "landscape") {
		getViewport().setWH(480, 300);
	}
});
*/

/**
 * Generate Background
 */
$(document).ready(function() {
	function generateBackground() {
		generateBackgroundStars("#background1", 10, 500*(1+1/4),  500*(1+1/4));
		generateBackgroundStars("#background2", 30, 500*(1+1/8),  500*(1+1/8));
		generateBackgroundStars("#background3", 60, 500*(1+1/16), 500*(1+1/16));
	}
	function generateBackgroundStars(id, num, maxx, maxy) {
		for (var i = 0; i < num; ++i) {
			$(id).append(createBackgroundStar(maxx, maxy));
		}
	}
	function createBackgroundStar(maxx, maxy) {
		var left = Math.floor(Math.random()*maxx - maxx/2);
		var top  = Math.floor(Math.random()*maxy - maxy/2);
		var star = Math.floor(Math.random()*6);

		var div = document.createElement("div");
		$(div).addClass("star-"+ star);
		$(div).css({ left: left +"px", top: top +"px" });
		return div;
	}

	generateBackground();
});

/**
 * Viewport
 */
$(document).ready(function() {
	var moving = false;
	var position = { x : 0, y : 0, toString : function() { return "{ x:"+ this.x +", y:"+ this.y +"}"; }};

	$(document).on("xtouchstart", "#viewport", function(event) {
		position.x = event.touches[0].pageX;
		position.y = event.touches[0].pageY;
		moving = true;
	});

	$(document).on("xtouchend", "#viewport", function(event) {
		moving = false;

		getViewport().store();
	});

	$(document).on("xtouchmove", "#viewport", function(event) {
		var touch = event.touches[0];
		var dx = touch.pageX - position.x;
		var dy = touch.pageY - position.y;

		position.x = touch.pageX;
		position.y = touch.pageY;

		if (!moving) return;

		getViewport().add({x:-dx, y:-dy});
	});

	getViewport().setUpdate(function(viewport) {
		var x = -viewport.x;
		var y = -viewport.y;
		var w = viewport.w;
		var h = viewport.h;

		function update(id, scale) {
			$(id).css({top: h/2+y*scale, left: w/2+x*scale});
		}

		update("#foreground", 1);
		update("#background1", 1/2);
		update("#background2", 1/4);
		update("#background3", 1/8);

		$("#message").html("UpdateViewport "+ x +":"+ y);
		getSystemManager().getSystems(function(system) {
			$("#system-"+ system.id).clearQueue();
			$("#system-"+ system.id).animate({top: system.y*viewport.s, left: system.x*viewport.s});
		});
		if (false) getSystemManager().getSystems(function(system) {
			var s = viewport.getScreen({x:system.x, y:system.y});
//			var w = viewport.getWorld({x:-w/2, y:-h/2});

			var minx = 16;
			var maxx = w-16;
			var miny = 86;
			var maxy = h-86;

			if (s.x < minx) $("#system-icon-"+ system.id).css({left: minx});
			else if (s.x > maxx) $("#system-icon-"+ system.id).css({left: maxx});
			else $("#system-icon-"+ system.id).css({left: s.x});

			if (s.y < miny) $("#system-icon-"+ system.id).css({top: miny});
			else if (s.y > maxy) $("#system-icon-"+ system.id).css({top: maxy});
			else $("#system-icon-"+ system.id).css({top: s.y});

			$("#system-icon-"+ system.id).html(s.x +" "+ s.y);
			if (s.x < minx ||
				s.x > maxx ||
				s.y < miny ||
				s.y > maxy) {
				$("#system-icon-"+ system.id).show();
			} else {
				$("#system-icon-"+ system.id).hide();
			}

			return false;
		});
	});
});

function centerViewport() {
	var w = $(window).width();
	var h = $(window).height();

	getViewport().set({w:w, h:h});
	$("#viewport").css({ width: w, height: h });
}

$(window).on("resize", function (event) {
	var w = $(window).width();
	var h = $(window).height();

	$("#message").html("resize: "+ w +":"+ h);
	centerViewport();
});

/**
 * StarMap
 */
var StarMap = {
	createSystem : function(system) {
		var div = document.createElement("div");
		div.id = "system-"+ system.id;
		$(div).addClass("space-system");
		$(div).addClass("xclickable");
		$(div).addClass("xdraggable");
		$(div).addClass("xdroppable");
		$(div).css({ left: system.x +"px", top: system.y +"px" });

		$(div).append((function() {
			var div = document.createElement("div");
			div.id = "system-target-"+ system.id;
			$(div).addClass("system-target");
			$(div).addClass("xdragignore");
			return div;
		}));
		$(div).append((function() {
			var div = document.createElement("div");
			div.id = "system-star-"+ system.id;
			$(div).addClass("system-star");
			$(div).addClass("xdragignore");
			return div;
		}));
		$(div).append((function() {
			var div = document.createElement("div");
			div.id = "system-force-"+ system.id;
			$(div).addClass("system-force");
			$(div).addClass("xdragignore");
			return div;
		}));
		$(div).append((function() {
			var div = document.createElement("div");
			div.id = "system-icon-"+ system.id;
			$(div).addClass("system-icon");
			$(div).addClass("xdragignore");
			return div;
		}));
		if (false) $(div).append((function() {
			var div = document.createElement("div");
			$(div).html(system.x +" "+ system.y);
			return div;
		}));

		system.uiUpdate = function() {
			StarMap.setPlayer(this.id);
			StarMap.setForce(this.id);
			StarMap.setTarget(this.id);
		};
		system.uiTarget = function() {
			StarMap.setTarget(this.id);
		}
		system.uiBuild = function() {
			StarMap.build(this.id);
		};
		system.uiMove = function(targetId) {
			StarMap.move(this.id, targetId);
		}
		system.uiBoom = function() {
			StarMap.boom(this.id);
		}
		system.uiConquer = function() {
			StarMap.conquer(this.id);
		}

		return div;
	},
	createStarMap : function() {
		$("#foreground").empty();

		var systems = getSystemManager().getSystems({});
		for (s in systems) {
			var system = systems[s];
			$("#foreground").append(this.createSystem(system));
			system.uiUpdate();
		}
	},

	setForce : function(systemId) {
		var system = getSystemManager().getSystem({id:systemId});
		if (!system) return;

//		$("#system-force-"+systemId).html( system.force > 1 ? (system.force-1) : "&nbsp;" );
		$("#system-force-"+systemId).html( system.force > 0 ? system.force : "&nbsp;" );
	},
	buildForce : function(systemId) {
		this.setForce(systemId);
		this.build(systemId);
	},
	setTarget : function(systemId) {
		var system = getSystemManager().getSystem({id:systemId});
		if (!system) return;

		if (system.target) {
			var target = getSystemManager().getSystem({id:system.target});
			if (!target) {
				console.log("SetTarget "+ systemId +" "+ system.target);
				return;
			}

			var dx = target.x - system.x;
			var dy = target.y - system.y;
			var deg = Math.atan2(dy, dx) *180/Math.PI;
			$("#system-target-"+ systemId)
				.css({ MozTransform: "rotate("+ deg +"deg)" })
				.css({ WebkitTransform: "rotate("+ deg +"deg)" })
				.css({ transform: "rotate("+ deg +"deg)" })
				.show();
		} else {
			$("#system-target-"+ systemId).hide();
		}
	},
	setPlayer : function(systemId) {
		var system = getSystemManager().getSystem({id:systemId});
		if (!system) return;

		var player = getPlayerManager().getPlayer({type:"default"});
		if (system.player) {
			player = getPlayerManager().getPlayer({id:system.player});
		}
		$("#system-"+ systemId).removeClass(function(index, css) {
			return (css.match(/\bplayer-\S+/g) || []).join(' ');
		});
		$("#system-"+ systemId).addClass("player-"+ player.id);
	},
	build : function(systemId) {
		var x = Math.random()*32;
		var y = Math.random()*32;
		var build = document.createElement("div");
		$(build).addClass("system-build");
		$(build).css({ top: y +"px", left: x +"px" });
		$(build).hide();
		$(build).fadeIn(300, function() {
			StarMap.setForce(systemId);
		}).delay(300).fadeOut(300, function() {
			$(this).remove();
		});
		$(build).appendTo("#system-"+ systemId);
	},
	move : function(systemId, targetId) {
		var system = getSystemManager().getSystem({ id:systemId });
		var target = getSystemManager().getSystem({ id:targetId });
		var dx = target.x - system.x +16;
		var dy = target.y - system.y +16;
		var fleet = document.createElement("div");
		$(fleet).addClass("system-fleet");
		$(fleet).delay(900).show(function() {
			StarMap.setForce(systemId);
		}).animate({ top: dy, left: dx }, 600, function() {
			$(this).remove();
			StarMap.setForce(targetId);
			StarMap.setTarget(systemId);
		});
		$(fleet).appendTo("#system-"+systemId);
	},
	boom : function(systemId) {
		var x = Math.random()*32;
		var y = Math.random()*32;
		var boom = document.createElement("div");
		$(boom).addClass("system-boom");
		$(boom).css({ top : y +"px" });
		$(boom).css({ left: x +"px" });
		$(boom).delay(1200).animate({ width: 64, height: 64, margin: -32 }, 600).fadeOut(function() {
			$(this).remove();
		});
		$(boom).appendTo("#system-"+ systemId);
	},
	conquer : function(systemId) {
		$("#system-"+ systemId).animate({ borderWidth: 0 }, 1500, function() {
			StarMap.setPlayer(systemId);
			StarMap.setTarget(systemId);
		});
	},
};

$(document).ready(function() {
	StarMap.createStarMap();
});
$(document).ready(function() {
	centerViewport();
});

/**
 * System Drag n Drop
 */
$(document).ready(function() {
	var dragsource = null;

	$(document).on("xdragstart", function(event) {
		dragsource = event.target;

		var image = document.createElement("img");
		$(image).attr("src", "gfx/ship16.png");
		event.dataTransfer.setDragImage(image, -8, -8);
	});

	$(document).on("xdrag", function(event) {
		// TODO: Update target
	});

	$(document).on("xdragend", function(event) {
	});

	$(document).on("xdragenter", function(event) {
		$(event.target).addClass("drop-target");
	});

	$(document).on("xdragover", function(event) {
	});

	$(document).on("xdragleave", function(event) {
		$(event.target).removeClass("drop-target");
	});

	$(document).on("xdrop", function(event) {
		$(event.target).removeClass("drop-target");

		if (dragsource == event.target) {
			getGameManager().clearTarget(dragsource.id);
		} else {
//			getGameManager().moveShip(dragsource.id, event.target.id, 1);
			var sourceId = dragsource.id.substr("system-".length);
			var targetId = event.target.id.substr("system-".length);
			getGameManager().setTarget(sourceId, targetId);
		}
	});

	$(document).on("xclick", ".space-system", function(event) {
		var systemId = this.id.substr("system-".length);
		getGameManager().clearTarget(systemId);
	});
});

/**
 * Game Menus
 */
$(document).ready(function() {
	getGameManager().addListener(function(message) {
		if (message == "state") {
			updateState();
		}
		if (message == "menu") {
			updateMenu();
		}
	});

	function updateState() {
		var state = getGameManager().state;

		if (state.id == GAME_STATE.INIT.id) {
			
		}
		if (state.id == GAME_STATE.PLAY.id) {
			
		}
		if (state.id == GAME_STATE.END.id) {
			
		}
	}
	function updateMenu() {
		function hide() {
			$("#main-menu").hide();
			$("#messages-menu").hide();
			$("#win-menu").hide();
			$("#loose-menu").hide();
		}
		var menu = getGameManager().menu;

		if (menu.id == MENU_STATE.NONE.id) {
			hide();
		}
		if (menu.id == MENU_STATE.MAIN.id) {
			hide();
			$("#main-menu").show();
		}
		if (menu.id == MENU_STATE.MESSAGES.id) {
			hide();
			$("#messages-menu").show();
		}
		if (menu.id == MENU_STATE.VICTORY.id) {
			hide();
			$("#win-menu").show();
		}
		if (menu.id == MENU_STATE.DEFEAT.id) {
			hide();
			$("#loose-menu").show();
		}
	}

	updateState();
	updateMenu();
});

/**
 * Game Buttons
 */
$(document).ready(function() {
	getGameManager().addListener(function(message) {
		if (message == "win") {
			$("#win-menu").show();
		}
		if (message == "loose") {
			$("#loose-menu").show();
		}
	});
	$("#win-resume").click(function() {
		getGameManager().setMenu(MENU_STATE.NONE);
	})

	$("#loose-resume").click(function() {
		getGameManager().setMenu(MENU_STATE.NONE);
	});

	$("#game-menu").click(function() {
		getGameManager().toggleMenu(MENU_STATE.MAIN);
	});
	$("#game-messages").click(function() {
		getGameManager().toggleMenu(MENU_STATE.MESSAGES);
	})
	$("#game-end").click(function() {
		getGameManager().setRandomTargets();
		getGameManager().endTurn();
	});
	$("#game-zoomin").click(function() {
		getViewport().add({s:1/2});
		getViewport().store();
	});
	$("#game-zoomout").click(function() {
		getViewport().add({s:-1/2});
		getViewport().store();
	});

	$("#main-new, #win-new, #loose-new").click(function() {
		getGameManager().newGame();
		StarMap.createStarMap();
		getViewport().set({ x:0, y:0 });

		getGameManager().setMenu(MENU_STATE.NONE);
	});
	$("#main-resume").click(function() {
		getGameManager().setMenu(MENU_STATE.NONE);
	});

	$("#messages-resume").click(function() {
		getGameManager().setMenu(MENU_STATE.NONE);
	});
});
